import Cookies from 'js-cookie'
const TokenKey = 'loginToken'
const uidkey = 'uid'

export function getToken() {
  return Cookies.get(TokenKey)
}

export function setToken(token) {
  return Cookies.set(TokenKey, token)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}
export function setUid(uid) {
  return localStorage.setItem(uidkey, uid);
}
export function getUid() {
  return localStorage.getItem(uidkey)
}
export function removeUid() {
  localStorage.removeItem(uidkey);
}


// 保存jobList
export function setJob(jobActive,jobList,) {
  const currentTimestamp = Date.now();
  sessionStorage.setItem('currentTimestamp', JSON.stringify(currentTimestamp));
  sessionStorage.setItem('jobActive', JSON.stringify(jobActive));
  return sessionStorage.setItem('jobList', JSON.stringify(jobList));
}

// 取本地任务key
export function getJob(key) {
  if(getCurrentTimestamp() ) {
    return JSON.parse(sessionStorage.getItem(key))
    
  } else {
    removeKey()
    return false
  }
  
}
// 删除 本地任务key

export function removeKey() {
  sessionStorage.removeItem('jobActive')
  sessionStorage.removeItem('jobList')
  sessionStorage.removeItem('currentTimestamp')

}

// 比较插入的时间和本地的时间 否则删除操作
function getCurrentTimestamp() {
  
  const timestamp = JSON.parse(sessionStorage.getItem('currentTimestamp'))
  console.log(timestamp, 'timestamp');
  // 获取当天晚上十二点的时间戳

  const currentDate = new Date();
  currentDate.setHours(0, 0, 0, 0);
  const startOfTodayTimestamp = currentDate.getTime();

  // 获取当前日期的结束时间戳（今天 23:59:59）
  const endOfTodayTimestamp =
    startOfTodayTimestamp + 24 * 60 * 60 * 1000 - 1;

  if (
    timestamp >= startOfTodayTimestamp &&
    timestamp <= endOfTodayTimestamp
  ) {
    return true
  } else {
    return false
  }
}

/**
 * 替换URL中的主机部分
 * @param {string} url - 需要替换的URL
 * @returns {string} - 替换后的URL
 */
export function switchHost(url) {
  const currentHost = "minio"; // 当前主机
  const targetHost = `${process.env.BASE_API_OSS}`; // 目标主机
  // 使用正则表达式替换主机部分
  const updatedUrl = url.replace(new RegExp(`\/\/${currentHost}:`), `//${targetHost}:`);
  return updatedUrl;
}


/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
  // return
  let config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  // console.log(tree);
  return tree;
}
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}
// 表单重置
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields();
  }
}

// 检查手机号是否正确

export function authPhone (phone) {
  const reg = /^1[3-9][0-9]\d{8}$/;
  return reg.test(phone)
}

//检查邮箱是否正确
export function authEmail (email) {
  const reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
  return reg.test(email)
}

